package data;

import hello.DataItem;
import hello.LatLon;
import hello.ShowData;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class dataprocess {
	
	private static dataprocess dp = null;
	private int i=0;
	public static dataprocess getInstance(){
		if(dp==null){
			dp = new dataprocess();
		}
		return dp;
	}
	
	public String insertData(String id,String val){
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Entity item = new Entity("testItem");
		item.setProperty("id", id);
		item.setProperty("val", val);
		datastore.put(item);
		return "";
	}
	
	
	public String insertData(String id,String lat,String lon,String spd,String dir){
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Entity itemLL = new Entity("latlon");
		itemLL.setProperty("lat", lat);
		itemLL.setProperty("lon", lon);
		Entity item = new Entity("trackers");
		item.setProperty("latlon",itemLL);
		item.setProperty("spd",spd);
		item.setProperty("dir",dir);
		datastore.put(itemLL);
		
		
		return "";
	}
	
	public String delData(){
		return "";
	}
	
	public String updData(){
		return "";
	}
	
	public DataItem getData(String id){
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Query q = new Query("testItem");
		q.addFilter("id", Query.FilterOperator.EQUAL, id);
		
		PreparedQuery pq  = datastore.prepare(q);
		if(pq==null){
			return null;
		}

		DataItem dataItem = new DataItem();
		dataItem.setTitle("001");
		dataItem.setImage("/img/blue.png");
		double x = 39.9748 + i*0.001;
		double ll[] = {x, 116.3430};
		i++;
		dataItem.setLatlon(ll);
		ShowData showdata = new ShowData();

		dataItem.setShowdata(showdata);
		
//		for(Entity result :pq.asIterable()){
//			str += (String)result.getProperty("val")+";"; 
//		}

		return dataItem;
	}
	
}
